package com.onion.utils.utils;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import com.onion.utils.support.enums.OS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SystemUtils {

    private static Logger log = LoggerFactory.getLogger(SystemUtils.class);

    private static String classesPath = null;
    private static Date sys_startup_time = new Date();

    /**
     * 获取系统根路径
     * @return
     */
    public static String getSystemPath(){
        return System.getProperty("user.dir");
    }

    /**
     * 获取系统启动时间
     * @Description:
     * @return
     * @Return:Date
     * @Time:2017-2-6
     * @Author:Arno
     */
    public static Date getSystemStart(){
        return sys_startup_time;
    }

    /**
     * 获取.class文件根路径
     * @return
     */
    public static String getClassesRootPath(){
        if(classesPath == null){
            String path = SystemUtils.class.getResource("/").toString();
            if(path.startsWith("file:/")){
                if(getOS()==OS.WINDOWS){
                    classesPath = path.substring(6);
                }else{
                    classesPath = path.substring(5);
                }
            }else{
                classesPath = path;
            }
            log.info("获取classesPath:"+classesPath);
        }
        return classesPath;
    }

    /**
     * 获取所有文件列表
     * @param path
     * @param suffix
     * @return
     */
    public static List<String> getResources(String path, String suffix){
        try {
            Enumeration<URL> enums = SystemUtils.class.getClassLoader().getResources(path);
            if(enums!=null){
                List<String> listResources = new ArrayList<String>();
                while(enums.hasMoreElements()){
                    URL uri = enums.nextElement();
                    String strUri = uri.toString();
                    if(strUri.endsWith(suffix)){
                        listResources.add(strUri);
                    }
                }
                return listResources;
            }else{
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取ClassPath路径
     * @return
     */
    public static String getClassPath(){
        return System.getProperty("java.class.path");
    }

    /**
     * @Description:获取操作系统
     * @return
     * @Return:String
     * @Time:2017-3-27
     * @Author:Arno
     */
    public static OS getOS(){
        String os = System.getProperty("os.name").toLowerCase();
        if(os.startsWith("windows")){
            return OS.WINDOWS;
        }else{
            return OS.LINUX;
        }
    }

}